package employee_role

import (
	"goskeleton/app/global/variable"
	"goskeleton/app/model/auth"
	"goskeleton/app/model/employee"
	"goskeleton/app/utils/cur_userinfo"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// EmployeeRoleMiddleware 员工角色中间件
// 功能：获取用户员工ID，查询角色等级，如果是超级管理员或部门负责人，则查询该部门下所有员工ID并存入context
func EmployeeRoleMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		variable.ZapLog.Warn("正在执行员工角色中间件",zap.Any("employee_id",11111111111111))
		// 1. 获取当前用户的employeeId
		employeeId, exists := cur_userinfo.GetCurrentUserEmployeeId(context)
		if !exists || employeeId <= 0 {
			variable.ZapLog.Warn("无法获取当前用户的员工ID")
			context.Next()
			return
		}
		variable.ZapLog.Warn("当前用户的员工ID", zap.Int("employee_id", employeeId))
		// 2. 查询该员工关联的所有组织岗位信息
		authPostMembersModel := auth.CreateAuthPostMembersModelFactory("")
		orgPosts := authPostMembersModel.GetByEmployeeId(employeeId)
		variable.ZapLog.Warn("当前用户的组织岗位信息", zap.Any("org_posts", orgPosts))
		// 如果没有找到关联的组织岗位，继续执行
		if len(orgPosts) == 0 {
			variable.ZapLog.Info("当前员工未关联任何组织岗位", zap.Int("employee_id", employeeId))
			context.Next()
			return
		}

		// 3. 查询这些组织岗位的角色等级
		authOrgPostModel := auth.CreateAuthOrganizationFactory("")
		var departmentIds []int
		isAdminOrManager := false

		for _, orgPost := range orgPosts {
			// 查询组织岗位详情
			var orgPostDetail auth.AuthOrganizationPostModel
			err := authOrgPostModel.GetById(orgPost.FrAuthOrganizationPostId, &orgPostDetail)
			if err != nil {
				variable.ZapLog.Error("查询组织岗位详情失败",
					zap.Int("org_post_id", orgPost.FrAuthOrganizationPostId),
					zap.Error(err))
				continue
			}
			variable.ZapLog.Info("组织岗位详情", zap.Any("org_post_detail", orgPostDetail))
			// 检查角色等级，1为超级管理员，2为部门负责人
			if orgPostDetail.RoleLevel == 1 || orgPostDetail.RoleLevel == 2 {
				isAdminOrManager = true
				// 收集部门ID（这里假设组织岗位ID就是部门ID，根据实际数据结构可能需要调整）
				departmentIds = append(departmentIds, orgPost.FrAuthOrganizationPostId)
			}
		}

		// 4. 如果是超级管理员或部门负责人，查询该部门下的所有员工ID

		var employeeIds []int
		if isAdminOrManager && len(departmentIds) > 0 {
			// 查询部门下的所有员工
			employeeModel := employee.CreateEmployeeFactory("")
			// 这里假设departmentIds可以直接用于查询员工，根据实际数据结构可能需要调整
			_, employees := employeeModel.ListData(0, 10000, "id ASC", "", 0, 0, "", "", departmentIds, 0)

			// var employeeIds []int
			for _, emp := range employees {
				employeeIds = append(employeeIds, int(emp.Id))
			}

		
		}else{
			employeeIds = append(employeeIds, employeeId)
		}
	
		// 将员工ID列表存入context
		context.Set("department_employee_ids", employeeIds)
		context.Next()
	}
}
